package org.yoyo.classroom.controller;

import org.yoyo.classroom.domain.po.User;
import org.yoyo.classroom.domain.query.UserQuery;
import org.yoyo.classroom.result.Result;
import org.yoyo.classroom.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/admin/users")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 根据ID查询用户
     * @param id 用户ID
     * @return 包含用户对象的结果
     */
    @GetMapping("/{id}")
    public Result<User> getUserById(@PathVariable Long id) {
        User user = userService.getUserById(id);
        if (user != null) {
            return Result.success(user);
        } else {
            return Result.error("User not found");
        }
    }

    /**
     * 查询所有用户
     * @return 包含用户列表的结果
     */
    @GetMapping
    public Result<List<User>> getUsers(UserQuery query) {
        List<User> users = userService.getUsers(query);
        return Result.success(users);
    }
    /**
     * 插入用户
     * @param user 用户对象
     * @return 包含影响行数的结果
     */
    @PostMapping
    public Result<Integer> addUser(@RequestBody User user) {
        int rowsAffected = userService.addUser(user);
        return Result.success(rowsAffected);
    }

    /**
     * 更新用户
     * @param user 用户对象
     * @return 包含影响行数的结果
     */
    @PutMapping("/update")
    public Result<Integer> updateUser(@RequestBody User user) {
        int rowsAffected = userService.updateUser(user);
        return Result.success(rowsAffected);
//        System.out.println(user);
//        return null;
    }

    /**
     * 删除用户（逻辑删除）
     * @param id 用户ID
     * @return 包含影响行数的结果
     */
    @DeleteMapping("/{id}")
    public Result<Integer> deleteUser(@PathVariable Long id) {
        int rowsAffected = userService.deleteUser(id);
        return Result.success(rowsAffected);
    }


}
